package net.jalbum.filters;

import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import net.jalbum.filterManager.FilterProperties.FilterCategory;
import se.datadosen.jalbum.Msg;

public class FlipFilterPlugin extends BasicFilter {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7157802824057671770L;
	protected FlipControl flipControl;

	protected boolean flipVertically = false;
	protected boolean flipHorizontally = false;

	public FlipFilterPlugin() {
		this.name = Msg.getString(this, "filters.flip.name");
		this.shortName = Msg.getString(this, "filters.flip.shortName");
		this.icon = new ImageIcon(this.getClass().getResource("res/flip-horizontal.png"));
		this.author = "David Fichtmueller";
		this.version = "1.0";
		this.description = Msg.getString(this, "filters.flip.description");
		this.category = FilterCategory.OTHER;
		this.prescale = false;
		this.postscale = true;
		this.flipControl = new FlipControl(this);
	}

	@Override
	public JPanel getControls() {
		return this.flipControl;
	}

	@Override
	public BufferedImage renderImage(final BufferedImage input) {
		final BufferedImage out = new BufferedImage(input.getWidth(), input.getHeight(), input.getType());

		int xStart, xMultiplier, yStart, yMultiplier;
		if (this.flipVertically) {
			yStart = input.getHeight() - 1;
			yMultiplier = -1;
		} else {
			yStart = 0;
			yMultiplier = 1;
		}

		if (this.flipHorizontally) {
			xStart = input.getWidth() - 1;
			xMultiplier = -1;
		} else {
			xStart = 0;
			xMultiplier = 1;
		}

		for (int x = 0; x < input.getWidth(); x++) {
			for (int y = 0; y < input.getHeight(); y++) {
				out.setRGB(x, y, input.getRGB(xStart + x * xMultiplier, yStart + y * yMultiplier));
			}
		}

		return out;
	}

	public void flipVertically() {
		this.flipVertically = !this.flipVertically;
		this.renderImage();
	}

	public void flipHorizontally() {
		this.flipHorizontally = !this.flipHorizontally;
		this.renderImage();
	}

	@Override
	public void keyPressed(final KeyEvent arg0) {
		if (arg0.getKeyCode() == KeyEvent.VK_KP_LEFT || arg0.getKeyCode() == KeyEvent.VK_LEFT || arg0.getKeyCode() == KeyEvent.VK_RIGHT || arg0.getKeyCode() == KeyEvent.VK_KP_RIGHT) {
			this.flipVertically();
		} else if (arg0.getKeyCode() == KeyEvent.VK_KP_UP || arg0.getKeyCode() == KeyEvent.VK_UP || arg0.getKeyCode() == KeyEvent.VK_KP_DOWN || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
			this.flipHorizontally();
		}
	}

	public boolean isFlipVertically() {
		return this.flipVertically;
	}

	public void setFlipVertically(final boolean flipVertically) {
		this.flipVertically = flipVertically;
	}

	public boolean isFlipHorizontally() {
		return this.flipHorizontally;
	}

	public void setFlipHorizontally(final boolean flipHorizontally) {
		this.flipHorizontally = flipHorizontally;
	}
}
